<template>
  <div class="index">
    <div id="container"></div>
    <div class="condiv">
      <ul
        @click="aa(val,key)"
        :class="vae == key ? 'conul concolor': 'conul'"
        v-for="(val,key) in inputdata"
        :key="key"
      >
        <li>姓名：{{val.driverName}}</li>
        <li>车牌：{{val.carNumber}}</li>
        <li v-if="val.carType">车型： {{ val.carType}}</li>
        <li v-if="val.fleetName">车队： {{val.fleetName}}</li>
        <li v-if="val.driverAddress">司机位置：{{val.driverAddress}}</li>
        <li v-if="val.carAddress">车辆位置：{{val.carAddress}}</li>
        <li v-if="val.driverDate">司机位置最新时间：{{val.driverDate}}</li>
        <li v-if="val.carDate">车辆位置最新时间：{{val.carDate}}</li>
      </ul>
    </div>
  </div>
</template>

  <script styp="text/javascript">
var title,
  	content,
  _this,
  map,
  infoWindow,
  positions = [],
  input;
window.dang = function(val, fleid, catid, Type, name, dispname) {
  if(input){
    const se = sessionStorage.getItem("phone");
    const displays = se.substring(1, se.length - 1);
    const users = sessionStorage.getItem("user");
    const user = users.substring(1, users.length - 1);
    const token = JSON.parse(sessionStorage.getItem("token"));
    _this.axios({
       method: "post",
          url: `${_this.baseURL}/logistic/dispatch/insertOrderDispatchOne`,
          data: {
            orderId: input.id || '',
            driverId: fleid || '',
            carId: catid || '',
            dispatchName: user || '',
            dispathPhone: displays || '',
            nodeContent: `${user}指定给司机: ${dispname} 派送订单，完成订单调度`,
            nodeSegment: input.nodeSegment ? input.nodeSegment : null,
            roleNumber: Type == 3 ? 2 : 3
          },
          headers: {
            accessToken: token,
            equipmentType: "2",
            "Content-Type": "application/json"
          }
        }).then(res =>{
          if (res.data.state == 200) {
            _this.$message({
              message: "调度成功",
              type: "success",
              offset : 80
            });
            _this.$router.push({ path: "/Disp/Dispatch" });
          } else {
            _this.$message({
                message : res.data.msg,
                offset : 80
              });
          }
        })
  }
  return
  if (input) {
    const se = sessionStorage.getItem("phone");
    const displays = se.substring(1, se.length - 1);
    const users = sessionStorage.getItem("user");
    const user = users.substring(1, users.length - 1);
    const token = JSON.parse(sessionStorage.getItem("token"));
    if (Type == 3) {
      if (input.state == 2) {
        var vasea = `${_this.baseURL}/logistic/dispatchFleet/insertDispatchFleet`;
      } else if (input.state == 3 || input.state == 4) {
        if (!input.fleetdsId) {
          return _this.$message({
            message : "只能指派给司机",
            offset : 80
          });
        }
        var vasea = `${_this.baseURL}/logistic/dispatchFleet/updateDispatchFleet`;
      }
      _this
        .axios({
          method: "post",
          url: vasea,
          data: {
            orderId: input.id,
            dispatchName: user,
            fleetId: fleid,
            dispatchPhone: displays,
            nodeContent: `${user}指定给车队: ${name} 派送订单，完成订单调度`
          },
          headers: {
            accessToken: token,
            equipmentType: "2",
            "Content-Type": "application/json"
          }
        })
        .then(res => {
          //console.log(res)
          if (res.data.state == 200) {
            _this.$message({
              message: "调度成功",
              type: "success",
              offset : 80
            });
            _this.$router.push({ path: "/Disp/Dispatch" });
          } else {
            _this.$message(
              {
                message : res.data.msg,
                offset : 80
              });
          }
        });
    } else {
      if (input.state == 2) {
        var vasea = `${_this.baseURL}/logistic/dispatch/insertOrderDispatchOne`;
      } else if (input.state == 3 || input.state == 4) {
        var vasea = `${_this.baseURL}/logistic/dispatch/updateOrderDispatchOne`;
        if (input.fleetdsId) {
          return _this.$message({
            message : "只能指派给车队",
            offset : 80
          });
        }
      }
      _this
        .axios({
          method: "post",
          url: vasea,
          data: {
            orderId: input.id,
            driverId: val,
            carId: catid,
            dispatchPhone: displays,
            dispatchName: user,
            nodeContent: `${user}指定给司机: ${dispname} 派送订单，完成订单调度`
          },
          headers: {
            accessToken: token,
            equipmentType: "2",
            "Content-Type": "application/json"
          }
        })
        .then(res => {
          //console.log(res)
          if (res.data.state == 200) {
            _this.$message({
              message: "调度成功",
              type: "success",
              offset : 80
            });
            _this.$router.push({ path: "/Disp/Dispatch" });
          } else {
            _this.$message({
              message : res.data.msg,
              offset : 80
            });
          }
        });
    }
  } else {
    _this.$message({
      message : "无法调度",
      offset : 80
    });
  }
};
export default {
  data() {
    return {
      inputdata: [],
      vae: null
    };
  },
  mounted() {
    _this = this;
    new Promise((resolve, reject) => {
      _this
        .axios({
          methods: "get",
          // url: `http://113.98.254.118:5050/getDate`
           url: `${this.paiURL}/gps/findCarGpsInfoList`
        })
        .then(res => {
          if (res.data.state == 200) {
            let data = res.data.data
            for(let i in data){
              positions.push(data[i])
            }
            let arr = []
            var myGeo = new BMap.Geocoder();
            let carTime = ''
            let driverTime = ''
            let carArr = []
            let driverArr = []
            let SelectType = 0
            for(let i of positions){
               if(i.carDate && i.driverDate){
                 carTime = new Date(i.carDate).getTime()
                 driverTime = new Date(i.driverDate).getTime()
                 if(carTime - driverTime >=0){
                   arr = i.carAddress.split(',')
                   i['date'] = i.carDate

                   //i['who'] = '车辆位置'
                 }else{
                   arr = i.driverAddress.split(',')
                   i['date'] = i.driverDate

                   //i['who'] = '司机位置'
                 }
                 carArr = i.carAddress.split(',')
                 driverArr = i.driverAddress.split(',')
                 SelectType = 1
               }else{
                 if(i.carDate){
                    arr = i.carAddress.split(',')
                    i['date'] = i.carDate
                    carArr = i.carAddress.split(',')
                    SelectType = 2
                    driverArr = []
                 }
                 if(i.driverDate){
                   carArr = []
                    arr = i.driverAddress.split(',')
                    i['date'] = i.driverDate
                    driverArr = i.driverAddress.split(',')
                    SelectType = 3
                 }
               }
              i['driverAddresa'] = arr
              i['carpoint'] = carArr
              i['driverpoint'] = driverArr
                if(SelectType == 1){
                  myGeo.getLocation(new BMap.Point(i.driverAddresa[0],i.driverAddresa[1]), function(result){
                    if(result)
                    {
                        i.Address = result.address
                    }
                  })
                  myGeo.getLocation(new BMap.Point(i.carpoint[0],i.carpoint[1]), function(result){
                    if(result)
                    {
                        i.carAddress = result.address
                    }
                  })
                  myGeo.getLocation(new BMap.Point(i.driverpoint[0],i.driverpoint[1]), function(result){
                  if(result)
                  {
                      i.driverAddress = result.address
                  }
                 })
                }else if(SelectType == 2){
                  myGeo.getLocation(new BMap.Point(i.carpoint[0],i.carpoint[1]), function(result){
                    if(result)
                    {
                        i.carAddress = result.address
                        i.Address = result.address
                        //i.driverAddress = ''
                    }else{
                     i.driverAddress = '未知的地址'
                     i.Address = '未知的地址'
                     i.carAddress = '未知的地址'
                   }
                  })
                }else if(SelectType == 3){

                  myGeo.getLocation(new BMap.Point(i.driverpoint[0],i.driverpoint[1]), function(result){
                   if(result)
                   {
                       i.driverAddress = result.address
                       i.Address = result.address
                       //i.carAddress = ''
                   }else{
                     i.driverAddress = '未知的地址'
                     i.Address = '未知的地址'
                     i.carAddress = '未知的地址'
                   }
                  })

                }

            }
            this.inputdata = positions;
            resolve();
          // const data = JSON.parse(res.data.data);
          // // console.log(JSON.parse(res.data.data))
          // //console.log(data.data)
          //       var datas = [];
          //       for (let i in data.data) {
          // //	console.log(data.data[i])
          //      //data.data[i] = JSON.parse(data.data[i]);
          //         myGeo.getPoint(data.data[i].driverAddress, function(point) {
          // 	  //console.log(point)
          //           if (point) {
          //              //console.log([point.lng, point.lat])
          //             data.data[i].driverAddresa = [point.lng, point.lat];
          //             datas.push(data.data[i]);
          //             if (datas.length == data.keys.length ) {
          //               positions = datas;
          //               _this.inputdata = positions;
          //               resolve();
          //             }
          //           }
          //         },'深圳市');
          //       }
          } else {
              this.$message({
                message : "暂无车辆数据",
                offset : 80
              });
              //console.log(res.data)
              resolve();
          }
        });
    }).then(res => {
      var time = setTimeout(() => {
        map = new BMap.Map("container");
        var point = new BMap.Point(111.069288, 26.742627);
        map.centerAndZoom(point, 7);
        map.enableScrollWheelZoom(true);
        map.enableInertialDragging(true);
        var opts = {
          width: 290, // 信息窗口宽度
          enableMessage: true //设置允许信息窗发送短息
        };
        var myIcon = new BMap.Icon(
          "http://113.98.254.118:9098/pictures/2020/01/07/a09a083b2cc24d60b8f48624eed87521347.png",
          new BMap.Size(40, 30)
        );
        console.log(positions)
        for (var i = 0; i < positions.length; i++) {
          //console.log(positions[i].driverAddresa[0])
          //console.log(positions[i].driverAddresa[1])
          var point = new BMap.Point(
            positions[i].driverAddresa[0],
            positions[i].driverAddresa[1]
          );
          //console.log(positions)
          var marker = new BMap.Marker(point, { icon: myIcon }); // 创建标注
          var content = positions[i];
          map.addOverlay(marker); // 将标注添加到地图中
          new BMap.Convertor().translate(point,0,translateCallback); 
          addClickHandler(content, marker);
        }
        function translateCallback(point1){
          console.log('回调')
            var marker1 = new BMap.Marker(point1);
            map.addOverlay(marker1);
            var label = new BMap.Label("转换后的百度坐标",{offset:new BMap.Size(20,-10)});
            marker1.setLabel(label); //添加百度label
            map.setCenter(point1);
        }
        function addClickHandler(content, marker) {
          marker.addEventListener("click", function(e) {
            openInfo(content, e);
          });
        }
        function setCenter(value) {
          map.centerAndZoom(new BMap.Point(value[0], value[1]), 20);
        }
        function openInfo(content, e) {
          //console.log(content , e)
          var p = e.target;
          setCenter(content.driverAddresa);
          //console.log(input)
          if (input) {
            var contents = ''
            contents = `<div style="width:6rem"><div style="padding-top:.2rem">姓名: <span style="padding-left:.2rem">${
              content.driverName
            }</span></div>
              <div style="padding-top:.2rem">车牌: <span style="padding-left:.2rem">${
                content.carNumber
              }</span></div>
              <div style="padding-top:.2rem">车型: <span style="padding-left:.2rem">${
                content.carType == undefined ? "暂无车型信息" : content.carType
              }</span></div>
              <div style="padding-top:.2rem">最新位置: <span style="padding-left:.2rem">${
                content.Address
              }</span></div>
              <div style="padding-top:.2rem">最新时间: <span style="padding-left:.2rem">${
                content.date
              }</span></div>
              <div style="padding-top:.2rem">车队: <span style="padding-left:.2rem">${
                content.fleetName == null || content.fleetName == ""
                  ? "无"
                  : content.fleetName
              }</span></div>
              <div style="padding-top:.2rem">司机类型: <span >${
                content.driverType == 1
                  ? "公司自有"
                  : content.driverType == 2
                  ? "挂靠司机"
                  : "挂靠车队"
              }</span></div>
              <div style="text-align:center;padding-top:.2rem"><button onclick="window.dang(${
                content.driverId
              },${content.driverId},${content.carId},${content.driverType},'${
              content.fleetName
            }','${
              content.driverName
            }');" style="width:50%;cursor:pointer;height:.7rem;background-color:#FFFFFF;border:1px solid red;border-radius:15px;">调度</button></div>`;
          } else {
            var contents = ''
            contents = `<div style="width:6rem"><div style="padding-top:.2rem">姓名: <span style="padding-left:.2rem">${
              content.driverName
            }</span></div>
              <div style="padding-top:.2rem">车牌: <span style="padding-left:.2rem">${
                content.carNumber
              }</span></div>
              <div style="padding-top:.2rem">车型: <span style="padding-left:.2rem">${
                content.carType == undefined ? "暂无车型信息" : content.carType
              }</span></div>
              <div style="padding-top:.2rem">最新位置: <span style="padding-left:.2rem">${
                content.Address
              }</span></div>
              <div style="padding-top:.2rem">最新时间: <span style="padding-left:.2rem">${
                content.date
              }</span></div>`;
          }
          var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
          var infoWindow = new BMap.InfoWindow(contents, opts); // 创建信息窗口对象
          map.openInfoWindow(infoWindow, point); //开启信息窗口
        }
      }, 30);
    });
  },
  beforeDestroy(){
    positions = []
  },
  methods: {
    aa(value, key) {
      this.vae = key;
      //console.log(input)
      map.centerAndZoom(
        new BMap.Point(value.driverAddresa[0], value.driverAddresa[1]),
        20
      );
      var opts = {
        width: 290, // 信息窗口宽度
        enableMessage: true //设置允许信息窗发送短息
      };
      if (input) {
        var contents = `<div style="width:6rem"><div style="padding-top:.2rem">姓名: <span style="padding-left:.2rem">${
          value.driverName
        }</span></div>
          <div style="padding-top:.2rem">车牌: <span style="padding-left:.2rem">${
            value.carNumber
          }</span></div>
          <div style="padding-top:.2rem">车型: <span style="padding-left:.2rem">${
            value.carType == undefined ? "暂无车型信息" : value.carType
          }</span></div>
          <div style="padding-top:.2rem">最新位置: <span style="padding-left:.2rem">${
            value.Address
          }</span></div>
          <div style="padding-top:.2rem">最新时间: <span style="padding-left:.2rem">${
            value.date
          }</span></div>
          <div style="padding-top:.2rem">车队: <span style="padding-left:.2rem">${
            value.fleetName == null || value.fleetName == ""
              ? "无"
              : value.fleetName
          }</span></div>
          <div style="padding-top:.2rem">司机类型: <span >${
            value.driverType == 1
              ? "公司自有"
              : value.driverType == 2
              ? "挂靠司机"
              : "挂靠车队"
          }</span></div>
          <div style="text-align:center;padding-top:.2rem"><button onclick="window.dang(${
            value.driverId
          },${value.driverId},${value.carId},${value.driverType},'${
          value.fleetName
        }','${
          value.driverName
        }');" style="width:50%;cursor:pointer;height:.7rem;background-color:#FFFFFF;border:1px solid red;border-radius:15px;">调度</button></div>`;
      } else {
        var contents = `<div style="width:6rem"><div style="padding-top:.2rem">姓名: <span style="padding-left:.2rem">${
          value.driverName
        }</span></div>
          <div style="padding-top:.2rem">车牌: <span style="padding-left:.2rem">${
            value.carNumber
          }</span></div>
          <div style="padding-top:.2rem">车型: <span style="padding-left:.2rem">${
            value.carType == undefined ? "暂无车型信息" : value.carType
          }</span></div>
          <div style="padding-top:.2rem">最新位置: <span style="padding-left:.2rem">${
            value.Address
          }</span></div>
          <div style="padding-top:.2rem">最新时间: <span style="padding-left:.2rem">${
            value.date
          }</span></div>`;
      }
      var point = new BMap.Point(
        value.driverAddresa[0],
        value.driverAddresa[1]
      );
      var infoWindow = new BMap.InfoWindow(contents, opts); // 创建信息窗口对象
      map.openInfoWindow(infoWindow, point); //开启信息窗口
    },
    findindata() {
      if (this.$route.query.rows) {
        var data = JSON.parse(this.$route.query.rows);
        input = data;
        //console.log(input)
      } else {
        input = null;
      }
    },
    dang(val) {
      //console.log(val)
    },
    taggingMap(){
      this.axios({
        method: 'get',
        url: `${this.paiURL}/gps/findCarGpsInfoList`
      }).then(res =>{
        let data = res.data.data
        //console.log(data)
        //console.log(typeof data)
        let positions = []
        for(let i in data){
          positions.push(data[i])
        }
        let arr = []
        var myGeo = new BMap.Geocoder();
        for(let i of positions){
           arr = i.driverAddress.split(',')
           i['driverAddresa'] = arr
            myGeo.getLocation(new BMap.Point(i.driverAddresa[0],i.driverAddresa[1]), function(result){
            if(result)
            {
                i.driverAddress = result.address
            }
          })
        }
        //console.log(positions)
      })
    }
  },
  created() {
    //this.taggingMap()
    this.findindata();
  },
  watch: {
    $route: "findindata"
  }
};
</script>

<style scoped>
.index {
  width: 100%;
  height: 100%;
}
#container {
  height: 100%;
  width: 100%;
}
.condiv {
  position: absolute;
  left: 0;
  top: 0;
  width: 15%;
  min-width: 300px;
  height: 100%;
  overflow: scroll;
  background-color: #ffffff;
  z-index: 2000000;
}
.condiv .conul {
  margin: 0.2rem;
  padding: 0.1rem;
  border-bottom: 1px solid #cccccc;
  cursor: pointer;
  overflow: scroll;
}
.condiv .conul::-webkit-scrollbar {display:none}
.condiv .conul li{
      line-height: .6rem;
      letter-spacing: 1px;
}
.condiv .concolor {
  background: #cccccc;
}
</style>
